package com.commerce.product.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.commerce.common.entity.ProductReview;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.Map;

/**
 * 商品评价Mapper接口
 */
@Mapper
public interface ReviewMapper extends BaseMapper<ProductReview> {

    /**
     * 分页查询商品评价
     * 
     * @param page 分页参数
     * @param productId 商品ID
     * @param rating 评分筛选
     * @param withImages 是否有图片
     * @return 评价分页结果
     */
    Page<ProductReview> selectProductReviews(Page<ProductReview> page, 
                                           @Param("productId") Long productId,
                                           @Param("rating") Integer rating,
                                           @Param("withImages") Boolean withImages);

    /**
     * 获取商品评价统计
     * 
     * @param productId 商品ID
     * @return 统计信息
     */
    @Select("SELECT " +
            "COUNT(*) as totalReviews, " +
            "COALESCE(AVG(rating), 0) as averageRating, " +
            "SUM(CASE WHEN rating = 1 THEN 1 ELSE 0 END) as rating1Count, " +
            "SUM(CASE WHEN rating = 2 THEN 1 ELSE 0 END) as rating2Count, " +
            "SUM(CASE WHEN rating = 3 THEN 1 ELSE 0 END) as rating3Count, " +
            "SUM(CASE WHEN rating = 4 THEN 1 ELSE 0 END) as rating4Count, " +
            "SUM(CASE WHEN rating = 5 THEN 1 ELSE 0 END) as rating5Count, " +
            "SUM(CASE WHEN images IS NOT NULL AND images != '' THEN 1 ELSE 0 END) as withImagesCount " +
            "FROM product_reviews " +
            "WHERE product_id = #{productId} AND status = 1")
    Map<String, Object> selectProductReviewStats(@Param("productId") Long productId);

    /**
     * 分页查询用户评价
     * 
     * @param page 分页参数
     * @param userId 用户ID
     * @return 评价分页结果
     */
    Page<ProductReview> selectUserReviews(Page<ProductReview> page, @Param("userId") Long userId);

    /**
     * 检查用户是否已评价该商品
     * 
     * @param userId 用户ID
     * @param productId 商品ID
     * @param orderId 订单ID
     * @return 评价数量
     */
    @Select("SELECT COUNT(*) FROM product_reviews " +
            "WHERE user_id = #{userId} AND product_id = #{productId} AND order_id = #{orderId}")
    int countUserProductReview(@Param("userId") Long userId, 
                              @Param("productId") Long productId, 
                              @Param("orderId") Long orderId);
}
